#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, IceStorm
import sys, thread
Ice.loadSlice('--all -I../slice -I/usr/share/slice ../slice/Robots.ice')
import Robots

class CameraI (Robots.Camera):

    def __init__ (self, adapter):
        # Key   ==> Object identity.
        # Value ==> Agent.
        self.__agents = {}
        self.__mutex = thread.allocate_lock()
        self.__topicManager = None

        # Reference to the topic manager.
        try:
            base = adapter.getCommunicator().stringToProxy('Robots.IceStorm/TopicManager')
            self.__topicManager = IceStorm.TopicManagerPrx.checkedCast(base)
        except Ice.Exception, ex:
            sys.stdout.write('Invalid TopicManager: ' + str(ex))
            raise Ice.Exception

        # Team channel.
        try:
            self.__topic = self.__topicManager.retrieve('Camera');
            print 'Topic Camera retrieved!'
        except IceStorm.NoSuchTopic:
            self.__topic = self.__topicManager.create('Camera');
            print 'Topic Camera created!'

    def getRobotPos (self, robot, curr):
        pass

    def subscribe (self, agent, curr):
        self.__mutex.acquire()

        if self.__agents.has_key(agent.ice_getIdentity()):
            self.__mutex.release()
            raise Robots.AlreadySubscribed
        else:            
            self.__agents[agent.ice_getIdentity()] = agent
            self.__mutex.release()

    def unsubscribe (self, agent, curr):
        self.__mutex.acquire()
        try:
            self.__agents.pop(agent.ice_getIdentity())
        except KeyError:
            pass
        self.__mutex.release()
